<?PHP

class OP_PhpbbContentWidget extends OP_WidgetTemplate{
	function render(){
		if(!$current_modules = get_option('op_modules')){
			$current_modules = array();
			add_option('op_modules', $current_modules);
		}
		//  only render widget is user has phpBB module activated
		if(!array_key_exists('phpBB',$current_modules) || $current_modules['phpBB'] != 1) return;
		
		require_once(TEMPLATEPATH.'/op/modules/module.phpbb.php');
		
		$orderby = $this->values['orderby'] ? 'topic_'.$this->values['orderby'] : 'topic_last_post_id';
		$forum_content = OP_phpBB3::getRecentPosts($orderby);
		
		if($this->values['avatar'] == 'gravatar'){
			array_walk($forum_content,array(&$this,'add_avatar_by_ref'));			
		}

		$title = empty( $this->values['title'] ) ? __( 'Forum Posts' ) : apply_filters('widget_title', $this->values['title']);	
		
		echo $this->values['before_title'] . $title . $this->values['after_title'];
		include(TEMPLATEPATH.'/widgets/template.phpbb_content.php'); // Include widget template file
	}
	
	function add_avatar_by_ref(&$post){
		$post['avatar'] = get_avatar(get_profile('user_email',$post['author']),32);
	}
	
	function do_post($post){
		$title = strip_tags(stripslashes($post['title']));
		$orderby = stripslashes($post['orderby']);
		$avatar = stripslashes($post['avatar']);
		return compact( 'title' , 'orderby', 'avatar');
	}
	
	function options(){
		echo '<p>',
			'<input class="widefat" type="text" id="phpbb_content-title-'.$this->values['number'].'" name="widget_op_phpbb_content['.$this->values['number'].'][title]" value="'.wp_specialchars($this->values['title'], true).'" />',
			'<label>'.__('Order by').': </label>',
			'<select name="widget_op_phpbb_content['.$this->values['number'].'][orderby]">',
				'<option value="last_post_id" '.($this->values['orderby'] == 'last_post_id' ? 'SELECTED' : '').'>Newest Post</option>',
				'<option value="replies" '.($this->values['orderby'] == 'replies' ? 'SELECTED' : '').'>Number of Replies</option>',
				'<option value="views" '.($this->values['orderby'] == 'views' ? 'SELECTED' : '').'>Number of Views</option>',
			'</select>',
			'<label>'.__('Avatars to use').': </label>',
			'<select name="widget_op_phpbb_content['.$this->values['number'].'][avatar]">',
				'<option value="gravatar" '.($this->values['avatar'] == 'gravatar' ? 'SELECTED' : '').'>Gravatar</option>',
				'<option value="phpbb" '.($this->values['avatar'] == 'phpbb' ? 'SELECTED' : '').'>phpBB</option>',
			'</select>',
		'</p>';
	}
}

$widget = new OP_Widget('phpbb_content');
$widget->setMeta('OP phpBB Content',"Show content from phpBB");
$widget->setDefaults(array('title'=>'','orderby'=>'last_post_id','avatar'=>'gravatar'));

$opw_phpbb_content = new OP_PhpbbContentWidget($widget);
add_action('widgets_init', array($opw_phpbb_content, 'init'));

?>